package org.lhh.server.config.init;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.concurrent.TimeUnit;

@Component
public class KeyPairInit implements InitializingBean, DisposableBean {

    private static Logger logger = LoggerFactory.getLogger(KeyPairInit.class);

    public static KeyPair keyPair;

    private Thread keyPairThread;

    private volatile boolean toStop = false;

    private void init() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        keyPairGen.initialize(1024, new SecureRandom());
        keyPairThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (!toStop) {
                    keyPair = keyPairGen.generateKeyPair();

                    try {
                        TimeUnit.MILLISECONDS.sleep(1000 * 60 * 5);
                    } catch (InterruptedException e) {
                        //ignored
                    }
                }
            }
        });
        keyPairThread.start();
    }

    private void toStop() {
        toStop = true;
        keyPairThread.interrupt();
        try {
            keyPairThread.join();
        } catch (InterruptedException e) {
            //ignored
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        init();
    }

    @Override
    public void destroy() throws Exception {
        toStop();
    }


}
